<template>
  <view class="login">
    <!-- LOGO -->
    <u-image width="300rpx"
             height="300rpx"
             src="https://sagit-1306666585.cos.ap-guangzhou.myqcloud.com/takeout/default/SDWSH.jpg"></u-image>
    <!-- 授权 -->
    <view class="btn">
      <!-- #ifdef MP-WEIXIN -->
      <u-button type="success"
                ripple>微信登录</u-button>
      <!-- #endif -->
      <u-button type="primary"
                style="margin: 10rpx 0;"
                ripple
                @click="handleLogin('msg')">
        手机登录
      </u-button>
      <u-button type="warning"
                ripple
                @click="handleLogin('psd')">密码登录</u-button>
    </view>
    <!-- 声明 -->
    <text class="text">
      登陆代表您已同意
      <text>用户协议、隐私政策</text>
    </text>
    <!-- 登录弹层 -->
    <u-popup v-model="show"
             mode="bottom"
             height="700rpx"
             border-radius="50"
             closeable
             @close="handleClose">
      <view class="popu">
        <!-- 标题 -->
        <h3 style="font-size: 40rpx;">{{ type === 'psd' ? '密码' : '手机' }}登录</h3>
        <!-- 表单 -->
        <u-form :model="form"
                ref="uForm"
                class="form"
                label-width="180"
                rules="rules">
          <u-form-item prop="username"
                       label="手机"
                       left-icon="account">
            <u-input v-model="form.username" />
          </u-form-item>
          <u-form-item prop="password"
                       :label="type === 'psd' ? '密码' : '验证码'"
                       left-icon="lock">
            <u-input v-model="form.password"
                     :type="type === 'psd' ? 'password' : 'text'" />
            <!-- 验证码 -->
            <template v-if="type === 'msg'"
                      #right>
              <u-verification-code keep-running
                                   :seconds="seconds"
                                   @start="start"
                                   ref="uCode"
                                   @change="codeChange"></u-verification-code>
              <u-button @tap="getCode"
                        size="mini"
                        type="primary"
                        plain
                        style="font-size: 25rpx;">
                {{ tips }}
              </u-button>
            </template>
          </u-form-item>
        </u-form>
        <!-- 按键 -->
        <u-button type="success"
                  ripple
                  @click="btnLogin">登录</u-button>
        <!-- 登录方式 -->
        <h5 v-if="type === 'psd'">
          还未注册？
          <u @click="handleLogin('msg')">使用手机一键登录</u>
        </h5>
        <h5 v-else
            @click="handleLogin('psd')">使用账号密码登录</h5>
      </view>
    </u-popup>
  </view>
</template>

<script>
export default {
  data() {
    return {
      show: false,
      form: {
        username: 'test1',
        password: '123456',
      }, //表单数据
      rules: {
        // 字段名称
        username: [
          {
            required: true,
            message: '请输入正确的手机号',
            min: 0,
            max: 11,
            trigger: ['change', 'blur'],
          },
        ],
        password: [
          {
            required: true,
            message: '长度在6~18位',
            min: 6,
            max: 18,
            trigger: ['change', 'blur'],
          },
        ],
      }, //校验规则
      type: '', //登录方式
      seconds: 60,
      tips: '',
      code: {},
    }
  },
  computed: {
    from() {
      return this.$route.query.from || '/pages/mine/mine'
    },
  },
	/* 	//! 调试时关闭
  watch: {
    // 弹层状态 + type 变化时清空密码
    show(val) {
      this.form.password = ''
      // 弹层关闭时清空表单
      if (!val) this.$refs.uForm.resetFields()
    },
    type() {
      this.form.password = ''
    },
  }, */
  methods: {
    // 打开登录弹层
    handleLogin(type) {
      this.show = true
      this.type = type || ''
      this.$nextTick(() => this.$refs.uForm.setRules(this.rules))
    },
    // 关闭登录弹层
    handleClose() {
      this.show = false
      this.type = ''
    },
    // 登录
    async btnLogin() {
      const { cipherText, createTime } = this.code
      const { username, password } = this.form
      try {
        // 表单校验
        await this.$refs.uForm.validate()
        // 获取token userid
        let TOKEN = null
        let ID = null
        if (this.type === 'psd') {
          const { token, userId } = await this.$u.api.login(this.form)
          TOKEN = token
          ID = userId
        } else {
          const { token, userId } = await this.$u.api.msgLogin({
            phone: username,
            cipherText,
            createTime,
            plainText: password,
          })
          TOKEN = token
          ID = userId
        }
        console.log(ID)
        // 存入token
        this.$store.dispatch('user/login', { token: TOKEN, id: ID })
        // 跳转
        this.$Router.push(this.from)
      } catch (e) {
        console.log(e)
      }
    },
    // 验证码
    codeChange(text) {
      this.tips = text
    },
    async getCode() {
      if (!this.$refs.uCode.canGetCode) return this.$u.toast('请稍后重试')
      // 模拟向后端请求验证码
      uni.showLoading({
        title: '正在获取验证码',
      })
      try {
        this.code = await this.$u.api.msg({ phone: this.form.username })
        // 这里此提示会被this.start()方法中的提示覆盖
        this.$u.toast('验证码已发送')
        // 通知验证码组件内部开始倒计时
        this.$refs.uCode.start()
      } catch (e) {
        this.$u.toast(e)
      }
      uni.hideLoading()
    },
    start() {
      this.$u.toast('验证码已发送，五分钟内有效')
    },
  },
}
</script>

<style lang="scss" scoped>
.login {
  height: calc(100vh - 44px);
  width: 100vw;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: center;
  padding: 0 100rpx;
}
.btn {
  width: 100%;
}
.text {
  font-size: 28rpx;
  color: $u-tips-color;
  text {
    color: $u-type-primary;
  }
}
.popu {
  height: 700rpx;
  width: 100vw;
  padding: 50rpx;
  h3 {
    font-weight: bolder;
  }
  h5 {
    color: $u-light-color;
    margin-top: 10rpx;
    text-align: right;
  }
}
.form {
  width: 100%;
  margin: 50rpx 0;
  // display: flex;
  // justify-content: space-between;
  // align-items: center;
  // flex-direction: column;
  // height: 1000rpx;
}
</style>
